package cool.xinya.ess.security;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * shiro session 持久化储存 redis
 *
 * @author wangxiaolong
 * @date 2019/6/20.
 */
public class RedisSessionDAO extends AbstractSessionDAO {

    private final RedisTemplate<Serializable, Session> redisTemplate;
    private final ValueOperations<Serializable, Session> sessionOperations;

    public RedisSessionDAO(RedisTemplate<Serializable, Session> redisTemplate) {
        this.redisTemplate = redisTemplate;
        sessionOperations = redisTemplate.opsForValue();
    }

    @Override
    protected Serializable doCreate(Session session) {
        final Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        sessionOperations.set("security:session:" + sessionId, session, session.getTimeout(), TimeUnit.MILLISECONDS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return sessionOperations.get("security:session:" + sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        sessionOperations.set("security:session:" + session.getId(), session, session.getTimeout(), TimeUnit.MILLISECONDS);
    }

    public void updateValue(Session session) {
        Long expire = redisTemplate.getExpire("security:session:" + session.getId());
        if (expire <= 0) {
            return;
        }
        sessionOperations.set("security:session:" + session.getId(), session, expire, TimeUnit.SECONDS);
    }

    @Override
    public void delete(Session session) {
        final Serializable sessionId = session.getId();
        redisTemplate.delete("security:session:" + sessionId);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return sessionOperations.multiGet(redisTemplate.keys("security:session:*"));
    }
}
